import { useCurrentUser, useData, useTemplate } from '@sker/runtime';
import { HttpError, toSuccess, useRbac, useTransaction } from '@sker/core';
import { SysMenu } from '@sker/entities';
import { getTheme } from './theme';
export const saveSort = async () => {
    const data = useData();
    if (data.menus && data.menus.length > 0) {
        const toUpdates: any[] = [];
        data.menus.map((m: any) => {
            toUpdates.push({ id: m.id, displayorder: m.displayorder })
            if (m.children && m.children.length > 0) {
                m.children.map((c: any) => {
                    toUpdates.push({ id: c.id, displayorder: c.displayorder })
                })
            }
        })
        await useTransaction(async m => {
            return m.save(SysMenu, toUpdates)
        })
        return toSuccess({})
    }
    throw new HttpError(`参数错误`)
}

export const getMenu = async (): Promise<any> => {
    const [current] = useCurrentUser()
    if (!current) return { menus: [], theme: {} };
    const theme = await getTheme();
    const toTree = (list: SysMenu[], pname?: string): SysMenu[] => {
        const parent = list.filter(it => {
            if (pname) return it.pname === pname
            const tnames = list.map(it => it.name)
            if (tnames.includes(it.pname)) return false;
            return true;
        })
        if (parent.length > 0) {
            const topKey = parent.map(it => it.name)
            const other = list.filter(it => !(topKey.includes(it.name) || topKey.includes(it.pname)))
            const top = parent.map(p => {
                const items = list.filter(it => p.name === it.pname).sort((a, b) => a.displayorder - b.displayorder)
                p.children = toTree([
                    ...items,
                    ...other
                ], p.name)
                return p;
            })
            return [
                ...top,
            ]
        }
        return []
    }
    const tree = await useTransaction(async m => {
        const list = await m.find(SysMenu, { order: { displayorder: 'asc' } })
        const menus = await useRbac(async r => {
            const menus = await Promise.all(list.map(async it => {
                const res = await r.enforce(current.username, it.name, 'get')
                if (res) return it;
                return;
            }))
            return menus.filter(it => !!it);
        })
        return toTree(menus.sort((a, b) => a.displayorder - b.displayorder))
    })
    if (tree && tree.length) return { menus: tree, theme };
    const menus: any[] = [];
    return { menus, theme }
}
export const get = async () => {
    await useTemplate({ isDev: true })
}
